<script setup lang="ts">
defineOptions({
  name: "testTypeTrend"
});
import { ref, watch, getCurrentInstance, onMounted, nextTick, reactive, toRefs, computed, onUnmounted } from "vue";
import yearPicker from "@/views/common/energy/components/yearPickerSmall.vue";
import barTitle from "@/views/machine/components/barTitle/index.vue";
import type { UtilsEChartsOption } from "@pureadmin/utils";
import { PxMessage } from "px-ui";
import { getFabZone, queryChildByTypeCodeAndItemValue } from "@/api/machineClass";
import barCom from "@/views/common/energy/components/barCom/index.vue";
import { getTestTypeTrend } from "@/api/machineApi";
import { wasteWaterqueryListPage0 } from "@/api/machineClass";

interface Props {
  /**  有 title 时传入 */
  title?: string;
  /**  有 title 时传入 */
  type?: string;
  /**  有按钮时传入，传入后会有 btn-click 事件 */
  button?: string;
  /**  模块最低宽度，默认 330px */
  width?: number;
  /**  模块最低高度，默认 200px */
  height?: number;
  /**  是否需要背景阴影，默认为true */
  boxShadow?: boolean;
  /**  是否需要圆角，默认为true */
  borderRidus?: boolean;
  /**  是否暗色，默认为false */
  dark?: boolean;
  /**按钮组 */
  chartParams?: any | {};
}

const props = withDefaults(defineProps<Props>(), {
  title: "AMC检测指标累计趋势",
  dark: false,
  width: 330,
  height: 200,
  boxShadow: false,
  borderRidus: false
});

interface queryForm {
  queryTimeGranularity?: string;
  level?: string;
  startTime?: string;
  endTime?: string;
}

type itemStyleType = {
  [key: string]: string;
};

interface dataType {
  name: string;
  value: number;
  itemStyle?: itemStyleType;
}

const emits = defineEmits(["btn-click", "reset"]);

const areaData = ref<any>([]);
const btnData = ref<any>([]);

const echartsRef = ref<InstanceType<typeof barCom> | null>(null);

const chartsOption = ref(null);

const chartsLoading = ref(false);

const echartsKey = ref<string>(Math.random().toString(36).slice(2, 10));

const defaultTime: [Date, Date] = [new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)];

const title_height = computed(() => (props.title ? "38px" : "0px"));
const min_width = computed(() => `${props.width}px`);
const min_height = computed(() => `${props.height}px`);

const energyType = ref("all");

const tablePieKey = ref(Date.now());

const { proxy }: any = getCurrentInstance();

const queryParams = ref<queryForm>({
  queryTimeGranularity: "Daily",
  level: ""
});

const types = ref<Array<string>>([]);

const queryTypeParams = ref({
  energyType: "Electricity"
});

// 定义数据
const dateRange = ref<any>([]);

const yearStart = ref("");
const yearEnd = ref("");
// 可选择区间，initYear传参，不传则所有年份有效，小于0判断一下？
const dateValue = ref<any>({ startYear: new Date().getFullYear(), endYear: new Date().getFullYear() });
// const dateValue = ref<any>({});
// 选完/输入完成的回调
const updateStatisticYear: any = (startYear: number, endYear: number) => {
  console.log("选中年份", startYear, endYear);
  dateRange.value = [startYear ? startYear.toString() : "", endYear ? endYear.toString() : ""];
  yearStart.value = `${startYear}-01-01 00:00:00`;
  yearEnd.value = `${endYear}-12-31 23:59:59`;
};

const pageData = ref<any>({});

const costOptions = ref({});

const dataList = ref<any>([]);

// 合并同类项数组
const mergeDataByProperty = (arr, type) => {
  const merged = [];
  let propertyValues = {};
  const keyArr: any = Array.from(new Set(arr.map(item => item.point))) || [];
  for (const val in keyArr) {
    propertyValues[keyArr[val]] = [];
    console.log(val);
    arr.forEach(item => {
      if (item.point === keyArr[val]) {
        propertyValues[keyArr[val]].push({
          name: item[type],
          value: Number(item.sum_value)
        });
      }
    });
  }
  return propertyValues;
};

const clickHandler = () => emits("btn-click");

const getXiasDataName = name => {
  let str = name || "";
  if (queryParams.value.queryTimeGranularity === "Daily") {
    return str.substring(0, 10);
  } else if (queryParams.value.queryTimeGranularity === "Monthly") {
    return str.substring(0, 7);
  } else {
    return str.substring(0, 4);
  }
};

const getPageData = async () => {
  const params = {
    startTime: queryParams.value.startTime,
    endTime: queryParams.value.endTime,
    zones: areaData.value,
    types: types.value
  };
  chartsLoading.value = true;
  const res: any = await getTestTypeTrend(params).catch(error => {
    chartsLoading.value = false;
  });
  console.log(res, "=========================");
  // 预测数据
  let spcList0 = [];
  if (res[0] && Object.keys(res[0]).length) {
    spcList0 =
      (Object.keys(res[0]).length &&
        Object.keys(res[0]).map(e => {
          return {
            indicatorName: e,
            pointValues: res[0][e].map(item => {
              return {
                time: item.dateTimeResult,
                ...item
              };
            })
          };
        })) ||
      [];
  }
  // 实际数据
  let spcList1 = [];
  if (res[1] && Object.keys(res[1]).length) {
    spcList1 =
      (Object.keys(res[1]).length &&
        Object.keys(res[1]).map(e => {
          return {
            indicatorName: e,
            pointValues: res[1][e].map(item => {
              return {
                time: item.dateTimeResult,
                ...item
              };
            })
          };
        })) ||
      [];
  }

  const spcList = spcList0.concat(spcList1);
  console.log(spcList, spcList0, spcList1, "=====================");
  if (!spcList.length) {
    costOptions.value = null;
    chartsLoading.value = false;
    return;
  }
  const obj: any = spcList[0];
  const series =
    spcList &&
    spcList.map((e, ind) => {
      return {
        // data: [400, 400, 400, 400, 400, 400],
        data: e.pointValues.length > 0 ? e.pointValues.map(item => item.value) : [],
        type: "line",
        name: e.indicatorName
        // areaStyle: {
        //   opacity: 0.15
        // },
        // symbol: "none"
        // markLine: {
        //   symbol: "none",
        //   data: [
        //     {
        //       name: "USL值",
        //       yAxis: Number(e.uslValue),
        //       lineStyle: {
        //         color: "#A600FF",
        //         wideh: "1",
        //         type: "solide"
        //       },
        //       label: {
        //         position: "insideEndTop",
        //         formatter: `USL值${e.uslValue}`,
        //         color: "#A600FF",
        //         fontWeight: 600
        //       }
        //     },
        //     {
        //       name: "UCL值",
        //       yAxis: Number(e.uclValue),
        //       lineStyle: {
        //         color: "#FF0000",
        //         wideh: "1",
        //         type: "dashed"
        //       },
        //       label: {
        //         position: "insideEndTop",
        //         formatter: `UCL值${e.uclValue}`,
        //         color: "#FF0000",
        //         fontWeight: 600
        //       }
        //     },
        //     {
        //       name: "UWL值",
        //       yAxis: Number(e.uwlValue),
        //       lineStyle: {
        //         color: "#FF9900",
        //         wideh: "1",
        //         type: "dashed"
        //       },
        //       label: {
        //         position: "insideEndTop",
        //         formatter: `UWL值${e.uwlValue}`,
        //         color: "#FF9900",
        //         fontWeight: 600
        //       }
        //     },
        //     {
        //       name: "Target值",
        //       yAxis: Number(e.targetValue),
        //       lineStyle: {
        //         color: "#00E272",
        //         wideh: "1",
        //         type: "solide"
        //       },
        //       label: {
        //         position: "insideEndTop",
        //         formatter: `Target值${e.targetValue}`,
        //         color: "#00E272",
        //         fontWeight: 600
        //       }
        //     },
        //     {
        //       name: "LWL值",
        //       yAxis: Number(e.lwlValue),
        //       lineStyle: {
        //         color: "#FF9900",
        //         wideh: "1",
        //         type: "dashed"
        //       },
        //       label: {
        //         position: "insideEndTop",
        //         formatter: `LWL值${e.lwlValue}`,
        //         color: "#FF9900",
        //         fontWeight: 600
        //       }
        //     },
        //     {
        //       name: "LCL值",
        //       yAxis: Number(e.lclValue),
        //       lineStyle: {
        //         color: "#FF0000",
        //         wideh: "1",
        //         type: "dashed"
        //       },
        //       label: {
        //         position: "insideEndTop",
        //         formatter: `LCL值${e.lclValue}`,
        //         color: "#FF0000",
        //         fontWeight: 600
        //       }
        //     },
        //     {
        //       name: "LSL值",
        //       yAxis: Number(e.lslValue),
        //       lineStyle: {
        //         color: "#A600FF",
        //         wideh: "1",
        //         type: "solide"
        //       },
        //       label: {
        //         position: "insideEndTop",
        //         formatter: `LSL值${e.lslValue}`,
        //         color: "#A600FF",
        //         fontWeight: 600
        //       }
        //     }
        //   ]
        // }
      };
    });
  const legendData = spcList && spcList.map(item => item.indicatorName);
  const resultObject: Record<string, boolean> = legendData.reduce(
    (acc: Record<string, boolean>, curr: string) => {
      acc[curr] = true;
      return acc;
    },
    {} as Record<string, boolean>
  );
  chartsOption.value = {
    color: "#ccc",
    title: {
      text: `Concentration Trends with Single-Sided SPC Line for ${props.type} Across FAB Zones`,
      left: "center",
      top: "10"
    },
    grid: {
      left: "40px",
      top: "40px",
      right: "40px",
      bottom: "10%",
      containLabel: true
    },
    legend: {
      id: "yourLegendId",
      type: "scroll",
      pager: {
        orient: "vertical",
        pageButtonItemGap: 5
      },
      data: legendData,
      orient: "horizontal",
      bottom: "0",
      itemGap: 20,
      selected: resultObject
    },
    tooltip: {
      trigger: "axis",
      confine: true
    },
    xAxis: {
      type: "category",
      boundarGap: false,
      data:
        obj.pointValues && obj.pointValues.length > 0
          ? obj.pointValues.map(item => formatDate(item.time))
          : ["11:00", "12:00", "13:00", "14:00", "15:00", "16:00"]
    },
    yAxis: {
      type: "value"
    },
    series: series
  };
  costOptions.value = chartsOption.value;
  chartsLoading.value = false;
  tablePieKey.value = Date.now();
};

const formatDate = timestamp => {
  const date = new Date(timestamp);
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, "0");
  const day = date.getDate().toString().padStart(2, "0");
  const h = date.getHours().toString().padStart(2, "0");
  const m = date.getMinutes().toString().padStart(2, "0");
  const s = date.getSeconds().toString().padStart(2, "0");
  return `${year}-${month}-${day} ${h}:${m}:${s}`;
};

// 获取当月第一天
const getCurrentMonthF = () => {
  let date = new Date();
  let y = date.getFullYear(); // 获取年
  let m: any = date.getMonth() + 1; // 获取月
  let d = "01";
  m = m < 10 ? "0" + m : m;
  return [y, m, d].join("-");
};

// 获取当月最后一天
const getCurrentMonthL = () => {
  let date = new Date();
  let y = date.getFullYear(); // 获取年
  let m: any = date.getMonth() + 1; // 获取月
  let d: any = new Date(y, m, 0).getDate();
  m = m < 10 ? "0" + m : m;
  d = d < 10 ? "0" + d : d;
  return [y, m, d].join("-");
};

const handleChangeFn = (val: string) => {
  //获取新的时间
  let date = new Date();
  //获取当前时间的年份转为字符串
  let year = date.getFullYear().toString();
  //获取月份，由于月份从0开始，此处要加1，判断是否小于10，如果是在字符串前面拼接'0'
  let month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1).toString() : (date.getMonth() + 1).toString();
  //获取天，判断是否小于10，如果是在字符串前面拼接'0'
  let da = date.getDate() < 10 ? "0" + date.getDate().toString() : date.getDate().toString();
  let y = date.getFullYear(); // 获取年
  let m: any = date.getMonth() + 1; // 获取月
  switch (val) {
    case "Daily":
      dateRange.value = [getCurrentMonthF(), getCurrentMonthL()];
      // queryParams.value.startTime = getCurrentMonthF() + " 00:00:00";
      // queryParams.value.endTime = getCurrentMonthL() + " 23:59:59";
      break;
    case "Monthly":
      dateRange.value = [`${year}-${month}`, `${year}-${month}`];
      // queryParams.value.startTime = dateRange.value[0] + "-01 00:00:00";
      // queryParams.value.endTime = dateRange.value[1] + "-31 23:59:59";
      break;
    case "Yearly":
      let yearS = new Date().getFullYear();
      let yearE = new Date().getFullYear();
      yearStart.value = `${yearS}-01-01 00:00:00`;
      yearEnd.value = `${yearE}-12-31 23:59:59`;
      break;
    default:
      break;
  }
};

// 校验时间范围不为空
const checkDate = () => {
  if (queryParams.value.queryTimeGranularity) {
    if (dateRange.value && dateRange.value.length) {
      return true;
    }
    if (queryParams.value.startTime && queryParams.value.endTime) {
      return true;
    }
  }
};

// 获取某月最后一天
const getMonthLastDay = (y, m) => {
  let date = new Date(y, m - 1, "01");
  date.setDate(1);
  date.setMonth(date.getMonth() + 1);
  let cdate = new Date(date.getTime() - 1000 * 60 * 60 * 24);
  return cdate.getDate();
};

const factoryName = ref("");
/** 搜索按钮操作 */
function handleQuery() {
  factoryName.value = queryParams.value.level;
  if (queryParams.value.queryTimeGranularity === "Daily") {
    queryParams.value.startTime = dateRange.value[0];
    queryParams.value.endTime = dateRange.value[1];
    // queryParams.value.startTime =
    //   queryParams.value.startTime.indexOf("00") != -1 ? queryParams.value.startTime : queryParams.value.startTime + " 00:00:00";
    // queryParams.value.endTime = queryParams.value.endTime.indexOf("59") != -1 ? queryParams.value.endTime : queryParams.value.endTime + " 23:59:59";
  } else if (queryParams.value.queryTimeGranularity === "Monthly") {
    queryParams.value.startTime = dateRange.value[0].indexOf("00") != -1 ? dateRange.value[0] : dateRange.value[0] + "-01 00:00:00";
    const d = getMonthLastDay(Number(dateRange.value[1].split("-")[0]), Number(dateRange.value[1].split("-")[1]));
    queryParams.value.endTime = dateRange.value[1].indexOf("59") != -1 ? dateRange.value[1] : dateRange.value[1] + "-" + d + " 23:59:59";
  } else {
    queryParams.value.startTime = yearStart.value;
    queryParams.value.endTime = yearEnd.value;
  }
  console.log(queryParams.value.startTime, queryParams.value.endTime);
  proxy.$refs["queryRef"].validate(valid => {
    if (!valid) return;
    if (queryParams.value.queryTimeGranularity) {
      if (!checkDate()) {
        return PxMessage({
          type: "warning",
          message: "时间范围不能为空"
        });
      }
    }
  });
  emits("reset", dateRange.value);
  getPageData();
}

const getColunms = () => {
  const params = Object.assign({}, props.chartParams);
  params.timeFrom = "";
  params.timeTo = "";
  wasteWaterqueryListPage0(params).then((response: any) => {
    if (response.total != 0) {
      btnData.value = response.data[0].testResult;
      const str = response.data[0].testResult.map(e => e.itemAttribute)[0];
      types.value = [str];
    } else {
      btnData.value = [];
      types.value = [];
    }
  });
};
/** 重置按钮操作 */
function resetQuery() {
  initQuery();
  emits("reset", dateRange.value);
}

// 反转数组
const reverseArray = (arr: any[]) => {
  let newArr = [];
  arr.forEach((item: any) => {
    newArr.unshift(item);
  });
  return newArr;
};

const initQuery = () => {
  queryParams.value.queryTimeGranularity = "Daily";
  //获取新的时间
  let date = new Date();
  //获取当前时间的年份转为字符串
  let year = date.getFullYear().toString();
  //获取月份，由于月份从0开始，此处要加1，判断是否小于10，如果是在字符串前面拼接'0'
  let month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1).toString() : (date.getMonth() + 1).toString();
  //获取天，判断是否小于10，如果是在字符串前面拼接'0'
  let da = date.getDate() < 10 ? "0" + date.getDate().toString() : date.getDate().toString();
  let y = date.getFullYear(); // 获取年
  let m: any = date.getMonth() + 1; // 获取月
  dateRange.value = [
    proxy.parseTime(new Date().getTime() - 30 * 24 * 60 * 60 * 1000 + 1000, "{y}-{m}-{d} {h}:{i}:{s}"),
    proxy.parseTime(new Date().getTime(), "{y}-{m}-{d} {h}:{i}:{s}")
  ];
  queryParams.value.startTime = dateRange.value[0];
  queryParams.value.endTime = dateRange.value[1];
  queryParams.value.level = "";
  getPageData();
};

const selectAllFn = async () => {
  const echartsCom = await echartsRef.value.el?.getEcharts();
  const selected = {};
  chartsOption.value.legend.data.forEach(name => {
    selected[name] = true;
  });
  chartsOption.value.legend.selected = selected;
  echartsCom.setOptions(chartsOption.value);
  nextTick(() => {
    echartsCom.resize();
  });
};

const inverseSelect = async () => {
  const echartsCom = await echartsRef.value.el?.getEcharts();
  const selected = {};
  chartsOption.value.legend.data.forEach(name => {
    selected[name] = false;
  });
  chartsOption.value.legend.selected = selected;
  echartsCom.setOptions(chartsOption.value);
  nextTick(() => {
    echartsCom.resize();
  });
};

onMounted(async () => {
  await getColunms();
  // 通过厂区字典查询区域
  const codes: any = await queryChildByTypeCodeAndItemValue({
    value: "CR_ALL_CODES",
    typeCode: "MCTS"
  });
  const areas: any = await queryChildByTypeCodeAndItemValue({
    value: "CSP01",
    typeCode: "MCTS"
  });
  areaData.value = areas.map(el => el.itemDesc);
  initQuery();
});
</script>

<template>
  <div class="today-task" :class="{ boxShadow, borderRidus, 'model-title-com-dark': dark }">
    <barTitle :title="title" />
    <div class="search_con">
      <px-checkbox-group v-model="types" :min="1" fill="#3B82F6" text-color="#ffffff">
        <px-checkbox-button v-for="btn in btnData" :key="btn.itemAttribute" :label="btn.itemAttribute">{{ btn.itemName }}</px-checkbox-button>
      </px-checkbox-group>
      <px-form ref="queryRef" :model="queryParams" class="custom-form-ui" :inline="true" label-width="100px">
        <!-- <px-form-item label="时间维度" prop="dataFormat">
          <px-radio-group v-model="queryParams.queryTimeGranularity" style="margin-left: 10px" @change="handleChangeFn">
            <px-radio size="small" label="Hourly">小时</px-radio>
            <px-radio size="small" label="Daily">日</px-radio>
            <px-radio size="small" label="Monthly">月</px-radio>
            <px-radio size="small" label="Yearly">年</px-radio>
          </px-radio-group>
        </px-form-item> -->
        <px-form-item label="" style="width: 430px">
          <!-- <px-time-picker
            v-if="queryParams.queryTimeGranularity === 'Hourly'"
            v-model="dateRange"
            is-range
            range-separator="-"
            format="HH"
            value-format="HH"
            start-placeholder="开始小时"
            end-placeholder="结束小时"
          /> -->
          <px-date-picker
            v-if="queryParams.queryTimeGranularity === 'Daily'"
            v-model="dateRange"
            value-format="YYYY-MM-DD HH:mm:ss"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :default-time="defaultTime"
          />
          <px-date-picker
            v-if="queryParams.queryTimeGranularity === 'Monthly'"
            v-model="dateRange"
            type="monthrange"
            value-format="YYYY-MM"
            range-separator="-"
            start-placeholder="开始月份"
            end-placeholder="结束月份"
          />
          <!-- <div v-else-if="queryParams.queryTimeGranularity === 'Yearly'" class="select_year">
            <px-date-picker v-model="queryParams.startTime" value-format="YYYY" type="year" placeholder="开始年份" />
            <span>&nbsp;-&nbsp;</span>
            <px-date-picker v-model="queryParams.endTime" value-format="YYYY" type="year" placeholder="结束年份" />
          </div> -->
          <div v-if="queryParams.queryTimeGranularity === 'Yearly'">
            <yearPicker ref="statisticPicker" :labelWidth="0" labelText="" :initYear="dateValue" @updateTimeRange="updateStatisticYear" />
          </div>
        </px-form-item>
        <!-- <px-form-item label="厂区">
          <px-select v-model="queryParams.level" clearable placeholder="请选择层级">
            <px-option v-for="item in systemList" :key="item.value" :label="item.name" :value="item.value" />
          </px-select>
        </px-form-item> -->
        <px-button type="primary" icon="" @click="handleQuery">搜索</px-button>
        <px-button icon="" @click="resetQuery">重置</px-button>
      </px-form>
    </div>
    <div v-loading="chartsLoading" class="echarts-chart-com">
      <div class="select-btn">
        <px-button size="small" icon="Select" @click="selectAllFn">全选</px-button>
        <px-button size="small" icon="SemiSelect" @click="inverseSelect">反选</px-button>
      </div>
      <barCom ref="echartsRef" :key="tablePieKey" :width="300" :height="200" :options="costOptions" />
    </div>
  </div>
</template>

<style lang="scss" scoped>
.today-task {
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  gap: 6px;
  width: 100%;
  height: 100%;
  padding: 16px 24px;
  background-color: #fff;

  .search_con {
    display: flex;
    flex-flow: row wrap;
    gap: 16px;
    justify-content: center;
  }

  .model-title-slot {
    display: flex;
    gap: 16px;
    align-items: center;

    .right-text {
      font-weight: 600;
      line-height: 1;
      color: var(--px-color-primary);
    }

    .px-icon {
      cursor: pointer;
    }
  }

  .echarts-chart-com {
    position: relative;
    width: 100%;
    height: calc(100% - v-bind(title_height));

    .select-btn {
      position: absolute;
      top: 0;
      left: 0;
      z-index: 100;
    }
  }
}

.px-form-item {
  margin-bottom: 0;
}

.boxShadow {
  box-shadow: 0 0 10px rgb(0 37 86 / 12%);
}

.borderRidus {
  border-radius: 4px;
}

.model-title-com-dark {
  color: #fff;
  background-color: #001e3b;
  border: 1px solid #83b2ff;
  box-shadow: inset 0 0 10px 0 #83b2ff;

  .title-text {
    color: #fff !important;
  }

  :deep(.model-title-com) {
    border-color: #00c2ff !important;
  }
}
</style>
